import vue from '@vitejs/plugin-vue'
import styleImport from 'vite-plugin-style-import'
import { UserConfigExport, ConfigEnv } from 'vite'
import { terser } from 'rollup-plugin-terser'
import { resolve } from 'path'
import { viteMockServe } from 'vite-plugin-mock'

const pathResolve = (dir: string): any => {
  return resolve(__dirname, '.', dir)
}
const alias: Record<string, string> = {
  '/@': pathResolve('src'),
  //解决开发环境下的警告 You are running the esm-bundler build of vue-i18n. It is recommended to configure your bundler to explicitly replace feature flag globals with boolean literals to get proper tree-shaking in the final bundle.
  'vue-i18n': 'vue-i18n/dist/vue-i18n.cjs.js'
}

export default ({ command }: ConfigEnv): UserConfigExport => {
  const prodMock = false
  return {
    base: '/',
    root: process.cwd(),
    resolve: {
      alias
    },
    // 服务端渲染
    server: {
      host: '0.0.0.0',
      // 是否开启 https
      https: false,
      port: 2020
      // 本地跨域代理
      // proxy: createProxy(VITE_PROXY)
    },
    plugins: [
      vue(),
      styleImport({
        libs: [
          // 按需加载element-plus
          {
            libraryName: 'element-plus',
            esModule: true,
            ensureStyleFile: true,
            resolveStyle: (name) => {
              name = name.slice(3)
              return `element-plus/packages/theme-chalk/src/${name}.scss`
            },
            resolveComponent: (name) => {
              return `element-plus/lib/${name}`
            }
          }
        ]
      }),
      viteMockServe({
        mockPath: 'mock',
        localEnabled: command === 'serve',
        prodEnabled: command !== 'serve' && prodMock,
        injectCode: `
          import { setupProdMockServer } from './mockProdServer';
          setupProdMockServer();
        `,
        logger: true
      })
    ],
    optimizeDeps: {
      include: [
        'element-plus/lib/locale/lang/zh-cn',
        'element-plus/lib/locale/lang/en'
      ]
    },
    build: {
      brotliSize: false,
      // 消除打包大小超过500kb警告
      chunkSizeWarningLimit: 2000,
      rollupOptions: {
        output: {
          // https://rollupjs.org/guide/en/#outputmanualchunks
          manualChunks: {
            vele: ['element-plus'],
            mock: ['mockjs'],
            vlib: ['vue']
            // "vlib": ['vue', 'vue-router', 'vuex'],
          }
        },
        plugins: [
          terser(),
          {
            name: 'renderReport',
            renderChunk(code, chunk) {
              console.log(
                '--------------rendering chunks---------------' +
                  chunk.name +
                  '  ' +
                  chunk.fileName +
                  ' ' +
                  code.length
              )
              return null
            },
            generateBundle(options, bundle) {
              console.log(
                '--------------generateBundle-----------------',
                bundle.fileName
              )
            },
            writeBundle(options, bundle) {
              console.log(
                '--------------writeBundle-----------------',
                bundle.fileName
              )
            },
            renderError(error) {
              console.log('---------------renderError-------------', error)
            }
          }
        ]
      }
    }
  }
}

// manualChunks(id) {
//   console.log(id);
//   if (id.includes('node_modules') && id.includes('element-plus')) {
//     return 'element-plus';
//   } else if(id.includes('node_modules') && id.includes('vue')){
//     return 'vue'
//   } else if (id.includes('node_modules')) {
//     return 'vendor';
//   }
// }

// manualChunks: {
//   'element-plus': ['element-plus'],
//   'lodash': ['lodash'],
// }
